// [2566]替换一个数字后的最大差值
struct Solution;

//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
    pub fn min_max_difference(num: i32) -> i32 {
        // 最小值通过替换0获得
        let min = Self::calc_num(10i32.pow(8), num, 0, std::cmp::min);
        // 最大值通过替换9获得
        let max = Self::calc_num(0, num, 9, std::cmp::max);
        max - min
    }

    fn calc_num(init_num: i32, num: i32, replace_num: i32, cmp: fn(i32, i32) -> i32) -> i32 {
        let num_vec = Self::get_vec_from_num(num);
        let mut result = init_num;
        let mut visited = std::collections::HashSet::new();
        for x in &num_vec {
            let mut cur = 0;
            if !visited.contains(x) {
                for (i, &y) in num_vec.iter().enumerate() {
                    let y = if y == *x { replace_num } else { y };
                    cur += y * 10i32.pow(i as _);
                }
                result = cmp(result, cur);
                visited.insert(x);
            }
        }
        result
    }

    fn get_vec_from_num(num: i32) -> Vec<i32> {
        let mut vec = vec![];
        let mut num = num;
        while num > 0 {
            vec.push(num % 10);
            num /= 10;
        }
        vec
    }
}
//leetcode submit region end(Prohibit modification and deletion)


#[test]
fn main() {
    let num = 11891;
    assert_eq!(Solution::min_max_difference(num), 99009);
    let num = 90;
    assert_eq!(Solution::min_max_difference(num), 99);
}